{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['00000000001111111111100000000000',\n",
       "       '00000000011111111111111000000000',\n",
       "       '00000000111111111111111000000000',\n",
       "       '00000001111111111111111000000000',\n",
       "       '00000000111111111111111110000000',\n",
       "       '00000000111111111111111110000000',\n",
       "       '00000001111111111000011100000000',\n",
       "       '00000001111110000000000000000000',\n",
       "       '00000001111100000000000000000000',\n",
       "       '00000001111100000000000000000000',\n",
       "       '00000001111100000000000000000000',\n",
       "       '00000011111111110000000000000000',\n",
       "       '00000001111111111110000000000000',\n",
       "       '00000011111111111110000000000000',\n",
       "       '00000011111111111110000000000000',\n",
       "       '00000011111111111110000000000000',\n",
       "       '00000001111111111111000000000000',\n",
       "       '00000000011100011111000000000000',\n",
       "       '00000000000000011111000000000000',\n",
       "       '00000000000000011111000000000000',\n",
       "       '00000000000000011111000000000000',\n",
       "       '00000000000000001111100000000000',\n",
       "       '00000000000000011111100000000000',\n",
       "       '00000000000000011111100000000000',\n",
       "       '00000000110000111111100000000000',\n",
       "       '00000000111111111111100000000000',\n",
       "       '00000000111111111111100000000000',\n",
       "       '00000000111111111110000000000000',\n",
       "       '00000000111111111100000000000000',\n",
       "       '00000000011111111110000000000000',\n",
       "       '00000000001111111100000000000000',\n",
       "       '00000000000000000000000000000000'], dtype='<U32')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "file_names = os.listdir(\"../work/digits/trainingDigits/\")\n",
    "label = '5_70.txt'.split('_')[0]\n",
    "txt = np.loadtxt('../work/digits/trainingDigits/5_70.txt',dtype='str')\n",
    "txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1024"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(''.join(txt))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "path='../work/digits/trainingDigits'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "\n",
    "函数功能：\n",
    "    读取文件夹中，文件内容\n",
    "\n",
    "输入：\n",
    "    文件夹路径\n",
    "\n",
    "输出：\n",
    "    df: (label + txt)\n",
    "\n",
    "'''\n",
    "\n",
    "\n",
    "def getFileDF(path):\n",
    "    # 1. 读取文件夹中，所有的文件名（包含label）\n",
    "    file_names = os.listdir(path)\n",
    "    labels = []\n",
    "    txts = []\n",
    "    for file_name in file_names:\n",
    "        label = file_name.split('_')[0]\n",
    "        file_path = path + '/' + file_name\n",
    "\n",
    "        # 2. 读取数据特征 （文件内容）\n",
    "        txt = np.loadtxt(file_path, dtype='str')\n",
    "        # 标签 + 数据\n",
    "        labels.append(label)\n",
    "        txts.append(''.join(txt))\n",
    "    \n",
    "    # 返回 DataFrame\n",
    "    return pd.DataFrame({\n",
    "        'label': labels,\n",
    "        'txt': txts\n",
    "    })\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "train = getFileDF('../work/digits/trainingDigits')\n",
    "test = getFileDF('../work/digits/testDigits')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>label</th>\n",
       "      <th>txt</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>0000000000000111100000000000000000000000000011...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0</td>\n",
       "      <td>0000000000011111000000000000000000000000001111...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0</td>\n",
       "      <td>0000000000000011000000000000000000000000000001...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0</td>\n",
       "      <td>0000000000001111000000000000000000000000000111...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0</td>\n",
       "      <td>0000000000000011111000000000000000000000000011...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1929</th>\n",
       "      <td>9</td>\n",
       "      <td>0000000000000000000100000000000000000000000000...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1930</th>\n",
       "      <td>9</td>\n",
       "      <td>0000000000000000000000010000000000000000000000...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1931</th>\n",
       "      <td>9</td>\n",
       "      <td>0000000000000000000000010000000000000000000000...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1932</th>\n",
       "      <td>9</td>\n",
       "      <td>0000000000000011111100000000000000000000000111...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1933</th>\n",
       "      <td>9</td>\n",
       "      <td>0000000000000011111100000000000000000000000001...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>1934 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     label                                                txt\n",
       "0        0  0000000000000111100000000000000000000000000011...\n",
       "1        0  0000000000011111000000000000000000000000001111...\n",
       "2        0  0000000000000011000000000000000000000000000001...\n",
       "3        0  0000000000001111000000000000000000000000000111...\n",
       "4        0  0000000000000011111000000000000000000000000011...\n",
       "...    ...                                                ...\n",
       "1929     9  0000000000000000000100000000000000000000000000...\n",
       "1930     9  0000000000000000000000010000000000000000000000...\n",
       "1931     9  0000000000000000000000010000000000000000000000...\n",
       "1932     9  0000000000000011111100000000000000000000000111...\n",
       "1933     9  0000000000000011111100000000000000000000000001...\n",
       "\n",
       "[1934 rows x 2 columns]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "```\n",
    "\n",
    "图片 接近 => 转化成 比较两个 字符串的相等\n",
    "\n",
    "输入:\n",
    "    字符串1\n",
    "    字符串2\n",
    "返回：\n",
    "    距离（）\n",
    "```\n",
    "```py\n",
    "def hamming(str1,str2)\n",
    "    return distance\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hamming(str1, str2):\n",
    "    len1 = len(str1)\n",
    "    len2 = len(str2)\n",
    "    if (len1 != len2):\n",
    "        return FileExistsError\n",
    "\n",
    "    # 初始化 距离\n",
    "    distance = 0\n",
    "    for i in range(0, len1):\n",
    "        if (str1[i] != str2[i]):\n",
    "            distance +=1\n",
    "    \n",
    "    return distance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ham(str1,str2):\n",
    "    return sum([a!=b for (a,b) in zip(str1,str2)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hammingDF(df,str2):\n",
    "    #遍历 df 的每一行\n",
    "    dists = []\n",
    "    for (i,row) in df.iterrows():\n",
    "        dist = ham(row[1],str2)\n",
    "        dists.append(dists)\n",
    "        #print(row)\n",
    "    return pd.DataFrame({\n",
    "        'dist': dists,\n",
    "        'label': df['label']\n",
    "\n",
    "    })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'9'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.iloc[1929,0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "309"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hamming(train.iloc[0,1],train.iloc[1929,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def knn(inX, df, k):\n",
    "    ## 步骤：相减 => 平方 => 求和 => 排序 => 根据k值筛选 分类结果\n",
    "    df_l = hammingDF(df, inX)\n",
    "    # print(df_l)\n",
    "    df_rank = df_l.sort_values(axis=0, by='dist', ascending=True)\n",
    "    # 筛选前 k 行\n",
    "    return df_rank.iloc[:k].value_counts('label').index[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def DigitsTest(train,test,k):\n",
    "    f_arr = []\n",
    "    for i, row in test.iterrows():\n",
    "        # 取 test 数据集 第 i 行的 txt\n",
    "        inX = row[1]\n",
    "        # print(inX)\n",
    "\n",
    "        # 把预测结果 保存到 数据中\n",
    "        f_arr.append(knn(inX, train, k))\n",
    "    \n",
    "    # 存储结果的 df\n",
    "    df_res = pd.DataFrame({\n",
    "        'f_label': f_arr\n",
    "    })\n",
    "\n",
    "    return (df_res['f_label'] == test['label']).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "DigitsTest(train,test,3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.9 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.9"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "774a858b74b9162cfeaabab2cd52460f9ad2aea53b492b6366c174bcba156af9"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
